package com.iob.coin.util;

import com.alibaba.fastjson.JSON;
import com.iob.coin.config.MainConfig;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: GuoXinyuan
 * @Date: 2021/5/28
 *
 * 封装用户登录Session存储相关逻辑
 */
public class UserSessionUtil {

    public static void setUserLoginState(int userId){
        HttpSession session = getHttpSession();
//        System.out.println("#UserSession: login session id: " + session.getId() + ";user id: " + userId);
        session.setAttribute(MainConfig.IDENTIFY_SESSION_KEY, userId);
    }

    public static void removeUserLoginState() {
        HttpSession session = getHttpSession();
        session.removeAttribute(MainConfig.IDENTIFY_SESSION_KEY);
        session.invalidate();
    }

    public static Integer getLoginUserId(){
        HttpSession session = getHttpSession();
//        System.out.println("#UserSession: get session id: " + session.getId() + ";user id: " + session.getAttribute(storeKey));
        return (Integer) session.getAttribute(MainConfig.IDENTIFY_SESSION_KEY);
    }

    public static HttpSession getHttpSession(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return request.getSession();
    }

}
